//
//  CustomSearchBar.m
//  Etion
//
//  Created by JingXing Wu on 11-11-29.
//  Copyright (c) 2011年 GuangZhouXuanWu. All rights reserved.
//

#import "XUISearchBar.h"
#import "UIStyleSkinManagerInternal.h"

@interface XUISearchBarTextField : UITextField
{
}

@end

@implementation XUISearchBarTextField

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect f = bounds;
    if (self.leftView == nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 5 + 2, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    else if (self.leftView != nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 25 + 2, bounds.origin.y, bounds.size.width - 50, bounds.size.height);
    return f;
}

- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    CGRect f = bounds;
    if (self.leftView == nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 5 + 2, bounds.origin.y, bounds.size.width - 10 - 4, bounds.size.height);
    else if (self.leftView != nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 25 + 2, bounds.origin.y, bounds.size.width - 50 - 4, bounds.size.height);
    return f;
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect f = bounds;
    if (self.leftView == nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 5 + 2, bounds.origin.y, bounds.size.width - 10 - 4, bounds.size.height);
    else if (self.leftView != nil&& self.rightView == nil)
        f = CGRectMake(bounds.origin.x + 25 + 2, bounds.origin.y, bounds.size.width - 50 - 4, bounds.size.height);
    return f;
}

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width - 20, (bounds.size.height - 15) / 2, 15, 15);
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(5 + 2, (bounds.size.height - 15) / 2, 15, 15);
}

- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width - 20, (bounds.size.height - 15) / 2, 15, 15);
}

@end

@interface XUISearchBar () <UITextFieldDelegate>
{
    UIImageView *_bgimage;
    
    BOOL _bScanbtnclick;
    CDropDownButton *_ddbtn;
    UIButton *_barCodeBtn;
    UIButton *_hideBtn;
    XUISearchBarStyleType _type;
    UIImage *_backgroundimage;
    id <XUISearchBarDelegate> _delegate;
    
    CGFloat _customAreaW;
    UITextField *_searchfield;
}
@end

@implementation XUISearchBar

@synthesize ddbtn = _ddbtn;
@synthesize type = _type;
@synthesize backgroundimage = _backgroundimage;
@synthesize delegate = _delegate;
@synthesize searchfield;
@synthesize customAreaW = _customAreaW;

#define CSB_MARGIN 5
#define HIDEBTN_W 40
#define CODEBAR_W 40
#define FILTER_W 80

- (id)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame styleType:XUISearchBarStyleTypeDefault];
}

- (id)initWithFrame:(CGRect)frame styleType:(XUISearchBarStyleType)type
{
    return [self initWithFrame:frame styleType:type customAreaWidth:frame.size.width];
}

- (id)initWithFrame:(CGRect)frame styleType:(XUISearchBarStyleType)type customAreaWidth:(CGFloat)customAreaWidth
{
    [super initWithFrame:frame];

    frame.origin = CGPointMake(0, 0);
    _customAreaW = customAreaWidth;

    [self create:frame type:type];

    _bgimage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchbar_bg.png"]];
    _bgimage.frame = self.bounds;
    _bgimage.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self insertSubview:_bgimage atIndex:0];


    return self;
}

- (void)create:(CGRect)frame type:(XUISearchBarStyleType)type
{
    frame.size.width = _customAreaW;
    
    [_hideBtn removeFromSuperview];
    [_hideBtn release];
    _hideBtn = nil;

    [_barCodeBtn removeFromSuperview];
    [_barCodeBtn release];
    _barCodeBtn = nil;

    [_ddbtn removeFromSuperview];
    [_ddbtn release];
    _ddbtn = nil;

    _type = type;

    CGFloat itemH = frame.size.height-2*CSB_MARGIN;
    if (type & XUISearchBarStyleTypeHideable)
    {
        _hideBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
        [_hideBtn SetTitle:@"取消"];
        [_hideBtn SetBackgroundImage:[[UIImage imageNamed:@"searchbar_btn_normal.png"] resizeableCenterImage]];
        [_hideBtn SetTitleColor:[UIColor blackColor]];
        [_hideBtn SetFont:[UIFont systemFontOfSize:15]];
        _hideBtn.frame = CGRectMake(CGRectGetWidth(frame) - HIDEBTN_W - CSB_MARGIN, (self.height - itemH) / 2, HIDEBTN_W, itemH);
        [_hideBtn addTarget:self action:@selector(hideButtonClecked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_hideBtn];
        frame.size.width -= HIDEBTN_W + CSB_MARGIN;
    }

    if (type & XUISearchBarStyleTypeCodeBar)
    {
        _barCodeBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
        [_barCodeBtn SetTitle:@"扫码"];
        [_barCodeBtn SetBackgroundImage:[[UIImage imageNamed:@"searchbar_btn_normal.png"] resizeableCenterImage]];
        [_barCodeBtn SetTitleColor:[UIColor blackColor]];
        [_barCodeBtn SetFont:[UIFont systemFontOfSize:15]];
        _barCodeBtn.frame = CGRectMake(CGRectGetWidth(frame) - CODEBAR_W - CSB_MARGIN, (self.height - itemH) / 2, CODEBAR_W, itemH);
        [_barCodeBtn addTarget:self action:@selector(barCodeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_barCodeBtn];
        frame.size.width -= CODEBAR_W + CSB_MARGIN;
    }

    if (type & XUISearchBarStyleTypeFilter)
    {
        CGRect f = CGRectMake(CGRectGetWidth(frame) - FILTER_W - CSB_MARGIN, (self.height - itemH) / 2, FILTER_W, itemH);
        if ((type & XUISearchBarStyleTypeDefault) != XUISearchBarStyleTypeDefault)
            f = CGRectMake(CSB_MARGIN, (self.height - itemH) / 2, CGRectGetWidth(frame) - 2 * CSB_MARGIN, itemH);
        _ddbtn = [[CDropDownButton alloc] initWithFrame:f];
        _ddbtn.delegate = self;
        _ddbtn.font = [UIFont systemFontOfSize:15];
        [self addSubview:_ddbtn];
        frame.size.width -= FILTER_W + CSB_MARGIN;
    }

    if (type & XUISearchBarStyleTypeDefault)
    {
        CGRect f = frame;
        f.origin.x += 5;
        f.origin.y += 5;
        f.size.width -= 10;
        f.size.height -= 10;

        if(_searchfield == nil)
        {
            _searchfield = [[XUISearchBarTextField alloc] initWithFrame:f];
            UIImageView *imgview = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchbar_leftsearch.png"]] autorelease];
            _searchfield.leftView = imgview;
            _searchfield.leftViewMode = UITextFieldViewModeAlways;
            _searchfield.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
            _searchfield.clearButtonMode = UITextFieldViewModeWhileEditing;
            _searchfield.placeholder = @"搜索";
            _searchfield.returnKeyType = UIReturnKeySearch;
            _searchfield.borderStyle = UITextBorderStyleRoundedRect;
            _searchfield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            _searchfield.font = [UIFont systemFontOfSize:15];
            _searchfield.delegate = self;
            [_searchfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
            [self addSubview:_searchfield];
            
            if ([CUIStyleSkinManager getCustomerBarBarStyleSkin] != nil)
            {
                _searchfield.returnKeyType = [CUIStyleSkinManager getCustomerBarBarStyleSkin].searchFieldReturnKeyType;
                _searchfield.borderStyle = [CUIStyleSkinManager getCustomerBarBarStyleSkin].searchFieldBorderStyle;
                _searchfield.background = [CUIStyleSkinManager getCustomerBarBarStyleSkin].searchFieldBorderImage;
            }
        }
        else
            _searchfield.frame = f;
    }
}

-(void)setCustomAreaW:(CGFloat)customAreaW
{
    CGFloat n = customAreaW - _customAreaW;
    _customAreaW = customAreaW;
    if (_type & XUISearchBarStyleTypeHideable)
    {
        _hideBtn.width += n;
    }
    if (_type & XUISearchBarStyleTypeCodeBar)
    {
        _barCodeBtn.width += n;
    }
    if (_type & XUISearchBarStyleTypeFilter)
    {
        _ddbtn.width += n;
    }
    if (_type & XUISearchBarStyleTypeDefault)
    {
        _searchfield.width += n;
    }
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];

    [_bgimage removeFromSuperview];
    [_bgimage release];
    _bgimage = nil;
}

- (void)setHiddenLabelText:(NSString *)hiddenLabelText
{
    [_hideBtn SetTitle:hiddenLabelText];
}

- (UITextField *)searchfield
{
    return _searchfield;
}

- (NSString *)searchText
{
    return _searchfield.text;
}

- (void)setSearchText:(NSString *)searchText
{
    _searchfield.text = searchText;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (_bScanbtnclick == YES)
        [_searchfield resignFirstResponder];

    if ([_delegate respondsToSelector:@selector(clearSearchField:)])
        return [_delegate clearSearchField:self];

    return YES;
}

- (void)hideButtonClecked:(UIButton *)btn
{
    if ([_delegate respondsToSelector:@selector(searchBarHideButtonClicked:)])
        [_delegate searchBarHideButtonClicked:self];
}

- (void)barCodeBtnClicked:(UIButton *)btn
{
    _bScanbtnclick = YES;

    [_searchfield resignFirstResponder];

    if ([_delegate respondsToSelector:@selector(barCodeClicked:)])
        [_delegate barCodeClicked:self];
}

- (void)dropDownButtonClick:(CDropDownButton *)button
{
    if ([_delegate respondsToSelector:@selector(dropDownButtonClick:dropDownBtn:)])
        [_delegate dropDownButtonClick:self dropDownBtn:_ddbtn];
}

- (void)setType:(XUISearchBarStyleType)type
{
    if (type == _type)
        return;

    [self create:self.bounds type:type];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ((_type & XUISearchBarStyleTypeDefault) != XUISearchBarStyleTypeDefault)
        return NO;

    if ([_delegate respondsToSelector:@selector(searchBarShouldBeginEditing:)])
        return [_delegate searchBarShouldBeginEditing:self];

    return YES;
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(searchBarTextDidBeginEditing:)])
        [_delegate searchBarTextDidBeginEditing:self];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(searchBarShouldEndEditing:)])
        return [_delegate searchBarShouldEndEditing:self];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(searchBarTextDidEndEditing:)])
        [_delegate searchBarTextDidEndEditing:self];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(searchBar:textDidChange:)])
        [_delegate searchBar:self textDidChange:textField.text];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    _bScanbtnclick = NO;

    if ((_type & XUISearchBarStyleTypeDefault) != XUISearchBarStyleTypeDefault)
        return NO;

    if ([_delegate respondsToSelector:@selector(searchBar:shouldChangeTextInRange:replacementText:)])
        return [_delegate searchBar:self shouldChangeTextInRange:range replacementText:string];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(searchBarSearchButtonClicked:)])
        return [_delegate searchBarSearchButtonClicked:self];
    return YES;
}

- (void)dropDownButtonReset:(CDropDownButton *)button
{
    if ([_delegate respondsToSelector:@selector(searchBarResetFilter:dropDownBtn:)])
        [_delegate searchBarResetFilter:self dropDownBtn:_ddbtn];
}

-(BOOL)resignFirstResponder
{
    return [_searchfield resignFirstResponder];
}

-(BOOL)becomeFirstResponder
{
    return [_searchfield becomeFirstResponder];
}

- (void)dealloc
{
    [_searchfield release];
    [_bgimage release];
    [_barCodeBtn release];
    [_backgroundimage release];
    [_ddbtn release];
    [_hideBtn release];

    [super dealloc];
}

@end